<?php

namespace app\admin\controller\extend;

use app\admin\controller\com\Admin;
use app\service\PluginsService;
use base\FileUtil;
use think\Request;

class Manager extends Admin
{
    protected $path;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->path =  DATA_PATH . 'plugins/plugin_back/';
    }


    //备份记录
    public function index()
    {
        $backupPath = $this->path;
        $data = [];
        $total = 0;
        if (is_dir($backupPath)) {
            $files = scandir($backupPath);
            foreach ($files as $file) {
                if ($file == '.' || $file == '..') {
                    continue;
                } else {
                    $total++;
                    $data[] = [
                        'name' => $file,
                        'add_time' => date('Y-m-d H:i:s',filemtime($backupPath . $file)),
                        'size' => round((filesize($backupPath . $file) / 1024 / 1024), 2) . ' M'
                    ];
                }
            }
            $time = array_column($data, 'add_time');
            array_multisort($time, SORT_DESC, $data);
        }
        $this->assign('data', $data);
        $this->assign('total', $total);
        return $this->fetch();
    }

    //下载文件
    public function download()
    {
        $name = input('name');
        if (empty($name)) {
            data_return('文件名称未设置', -1);
        }
        $backupPath =$this->path . trim($name);
        if (!file_exists($backupPath)) {
            data_return('文件不存在或已删除成功',-1);
        }
        if (is_file($backupPath)) {
            ob_start();
            header('Content-Type:application/zip');
            header('Content-disposition:attachment;filename=' . 'plugins_'.date('YmdHis') . '.zip');
            $filesize = filesize($backupPath);
            readfile($backupPath);
            header('Content-length:' . $filesize);
            ob_end_flush();
            exit();
        }
        data_return('文件不存在或已删除成功', -1);
    }

    //删除备份
    public function del()
    {
        $name = input('name');
        if (empty($name)) {
            data_return('文件名称未设置', -1);
        }

        $backupPath = $this->path. trim($name);

        if (!file_exists($backupPath)) {
            data_return('文件不存在或已删除成功', -1);
        }
        $res = @unlink($backupPath);
        if (!$res) {
            data_return('删除失败', -1);
        }
        data_return('操作成功', 0);
    }

    //开始备份
    public function backup()
    {
        $data = PluginsService::get_all_plugin_list();
        if (empty($data)) data_return('没有找到插件',-1);

        if (!is_dir($this->path)){
            mkdir($this->path,0775,true);
            chmod($this->path, 0775);
        }
        //临时目录
        $date_path = $this->path.date('Ymd').'/';

        $total = 0;
        if (is_dir($this->path)) {
            $files = scandir($this->path);
            foreach ($files as $file) {
                if ($file == '.' || $file == '..') {
                    continue;
                } else {
                    $total++;
                }
            }
        }
        if ($total >= 50) {
            data_return('当前备份数量已达上限，请删除旧备份重试', -1);
        }

        $readme = '插件是基于自己的系统开发，请在授权的情况下使用插件，版权归http://www.ok8.top所有,联系qq：1076963452。' . PHP_EOL;
        $readme .= '现在是' . date('Y年m月d日H时i分s秒') . '本次备份的插件应用列表如下：' . PHP_EOL;

        if ($data) {
            foreach ($data as $plugin) {
                $this->action_pack([
                    'plugin_tag' => $plugin['info']['plugin_tag'],
                    'date_path' => $date_path,
                    'tmp_dir' => $this->path . $plugin['info']['plugin_tag'] . '/',
                    'whiteList' => '',
                ]);

                $readme .= "========================================" . PHP_EOL;
                $readme .= "插件标识:" . $plugin['info']['plugin_tag'] . PHP_EOL;
                $readme .= "插件名称:" . $plugin['info']['name'] . PHP_EOL;
                $readme .= "插件版本:" . $plugin['info']['version'] . PHP_EOL;
                $readme .= "插件作者:" . $plugin['info']['author'] . PHP_EOL;
                $readme .= "插件作者联系方式:" . $plugin['info']['contact'] . PHP_EOL;
                $readme .= "插件描述:" . $plugin['info']['desc'] . PHP_EOL;
                $readme .= "========================================" . PHP_EOL;
            }
        }
        //打包日期目录
        if (is_dir($date_path)) {
            //最终目标
            $zipName = $this->path . md5(date('YmdHi')) . '.zip';//每分钟最多一个
            $zip = new \ZipArchive ();
            $zip->open($zipName, \ZipArchive::CREATE);

            PluginsService::createZip(opendir($date_path), $zip, $date_path, date('Ymd'));
            closedir();

            //设置应用标识
            $zip->addFromString('readme.txt', $readme);
            $zip->close();
             FileUtil::unlinkDir($date_path);
            data_return();
        }
        data_return('操作失败', -1);
    }

    /**
     * 打包下载
     */
    private function action_pack($params)
    {
        //临时目录
        $temp_dir = $params['tmp_dir'];
        //需要过滤的目录
        $whiteList = $params['whiteList'];
        //最终保存位置
        $backupPath = $params['date_path'];
        if (!is_dir($temp_dir)) {
            if (!mkdir($temp_dir, 0777, true)) {
                return data_return_arr('目录没有写入权限' . $temp_dir, -1);
            }
            chmod($temp_dir, 0777);
        }
        if (!is_dir($backupPath)) {
            mkdir($backupPath, 0777, true);
            chmod($backupPath, 0777);
        }

        //基本的文件路径
        $controller_path = APP_PATH . 'plugin/controller/' . $params['plugin_tag'];
        $view_path = APP_PATH . 'plugin/view/' . $params['plugin_tag'];
        $static_path = PUBLIC_PATH . 'static/plugins/' . $params['plugin_tag'];

        $fileName = $params['plugin_tag'] . '.zip';
        //最终目标
        $zipName = $temp_dir . $fileName;

        $zip = new \ZipArchive ();
        $zip->open($zipName, \ZipArchive::CREATE);

        if (is_dir($controller_path)) {
            PluginsService::createZip(opendir($controller_path), $zip, $controller_path, 'bs_controller', $whiteList);
            closedir();
        }

        if (is_dir($view_path)) {
            PluginsService::createZip(opendir($view_path), $zip, $view_path, 'bs_view');
            closedir();
        }

        if (is_dir($static_path)) {
            PluginsService::createZip(opendir($static_path), $zip, $static_path, 'bs_static');
            closedir();
        }
        PluginsService::createZip(opendir($temp_dir), $zip, $temp_dir, $params['plugin_tag']);
        closedir();
        //设置应用标识
        $zip->addFromString('说明.txt', "下载后请勿更改目录结构和文件结构，否则上传无法安装！！！\r\n created by " . $this->request->host());

        $zip->close();
        //移动文件
        if (is_file($zipName)) {
            //移动成功并清理目录
            if (copy($zipName, $backupPath . $fileName)) {
                unlink($zipName);
                rmdir($temp_dir);
            }
        }
        return data_return_arr('操作成功', 0);
    }

}